package com.runen.infinitemovement.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.runen.infinitemovement.R;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.GetTopIdEntity;
import com.runen.infinitemovement.model.entity.PictrueEntity;
import com.runen.infinitemovement.picker.ConvertUtils;
import com.runen.infinitemovement.picker.DatePicker;
import com.runen.infinitemovement.picker.WheelView;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.tool.UiUtil;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.PermissionUtils;
import com.runen.rxnetlibrary.utils.ToastUtils;
import com.runen.rxnetlibrary.utils.constant.PermissionConstants;
import com.runen.rxnetlibrary.utils.helper.DialogHelper;
import com.zhihu.matisse.Matisse;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ImprovePersonalDataActivity extends BaseActivity {
    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.top_btn_right)
    Button topBtnRight;
    @BindView(R.id.v_title_line)
    View vTitleLine;
    @BindView(R.id.rl_person_header)
    RelativeLayout rlPersonHeader;
    @BindView(R.id.iv_person_header)
    RoundedCornersImage ivPersonHeader;
    @BindView(R.id.edt_input_nickMame)
    EditText edtInputNickMame;
    @BindView(R.id.edt_input_synopsis)
    EditText edtInputSynopsis;
    @BindView(R.id.ll_sex_man)
    LinearLayout llSexMan;
    @BindView(R.id.ll_sex_woman)
    LinearLayout llSexWoman;
    @BindView(R.id.iv_man_check)
    ImageView ivManCheck;
    @BindView(R.id.iv_woman_check)
    ImageView ivWomanCheck;
    @BindView(R.id.tv_man_check)
    TextView tvManCheck;
    @BindView(R.id.tv_woman_check)
    TextView tvWomanCheck;
    @BindView(R.id.tv_complete)
    TextView tvComplete;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    private int sex = 1;
    private String headImgUrl;
    private String birthday;
    private List<Uri> avatar = new ArrayList<>();
    private int REQUEST_CODE_CHOOSE = 23;
    private String userIcon, userName;
    private int inTenant;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_improve_personal_data;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        userIcon = getIntent().getStringExtra("userIcon");
        userName = getIntent().getStringExtra("userName");
        inTenant = getIntent().getIntExtra("inTenant", 0);
        if (!TextUtils.isEmpty(userIcon)) {
            edtInputNickMame.setHint(userName);
        }
        topTitle.setText("完善个人资料");
        topBtnRight.setText("跳过");
        vTitleLine.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(userIcon)) {
            headImgUrl = userIcon;
            GlideUtils.loadImage(this, userIcon, ivPersonHeader);
        }
    }

    private void topId() {
        showDialog();
        new UserAPI().getTopId(new BaseResultCallback<GetTopIdEntity>() {
            @Override
            public void onResponse(GetTopIdEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    if (!TextUtils.isEmpty(response.data)) {
                        Intent intent = new Intent(ImprovePersonalDataActivity.this, CheckTeamActivity.class);
                        intent.putExtra("companyId", response.data);
                        startActivity(intent);
                        finish();
                    }
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                super.onError(e, body);
                dismissDialog();
            }
        });
    }

    @OnClick({R.id.top_btn_left, R.id.top_btn_right, R.id.rl_person_header, R.id.ll_sex_man, R.id.ll_sex_woman, R.id.tv_complete, R.id.tv_birthday})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.top_btn_right:
                if (inTenant != 4)
                    startActivity(new Intent(this, InputTeamCodeActivity.class));
                else
                    topId();
                break;
            case R.id.rl_person_header:
                onPermission();
                break;
            case R.id.ll_sex_man:
                sex = 1;
                ivManCheck.setImageResource(R.mipmap.ico_person_checked);
                ivWomanCheck.setImageResource(R.mipmap.ico_person_normal_check);
                tvManCheck.setTextColor(CommonUtil.getColor(R.color.color_333333));
                tvWomanCheck.setTextColor(CommonUtil.getColor(R.color.color_FF999999));
                break;
            case R.id.ll_sex_woman:
                sex = 2;
                ivManCheck.setImageResource(R.mipmap.ico_person_normal_check);
                ivWomanCheck.setImageResource(R.mipmap.ico_person_checked);
                tvManCheck.setTextColor(CommonUtil.getColor(R.color.color_FF999999));
                tvWomanCheck.setTextColor(CommonUtil.getColor(R.color.color_333333));
                break;
            case R.id.tv_complete:
                saveInfo();
                break;
            case R.id.tv_birthday:
                onYearMonthDayPicker(tvBirthday);
                break;
        }
    }

    /**
     * 获取拍照权限
     */
    private void requestCamera() {
        UiUtil.getImageSelectorConfig(this, REQUEST_CODE_CHOOSE);
    }

    @SuppressLint("WrongConstant")
    private void onPermission() {
        //请求动态权限
        PermissionUtils.permission(
                PermissionConstants.STORAGE,
                PermissionConstants.CAMERA,
                PermissionConstants.WRITE_EXTERNAL_STORAGE,
                PermissionConstants.ACCESS_COARSE_LOCATION)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(final ShouldRequest shouldRequest) {
                        DialogHelper.showRationaleDialog(shouldRequest);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        requestCamera();
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever,
                                         List<String> permissionsDenied) {
                        if (!permissionsDeniedForever.isEmpty()) {
                            DialogHelper.showOpenAppSettingDialog();
                        }
                    }
                })
                .request();
    }

    private void saveInfo() {
        showDialog();
        String string = edtInputNickMame.getText().toString();
        if (!TextUtils.isEmpty(string)) {
            userName = string;
        }

        JSONObject object = new JSONObject();
        try {
            object.put("sex", sex);
            object.put("birthday", birthday);
            object.put("headImgUrl", headImgUrl);
            object.put("nickname", userName);
            object.put("introduce", edtInputSynopsis.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new UserAPI().onSavePerson(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                dismissDialog();
                if (response.getCode() == 0) {
                    if (inTenant != 4) {
                        startActivity(new Intent(ImprovePersonalDataActivity.this, InputTeamCodeActivity.class));
                    } else {
                        topId();
                    }
                    ToastUtils.showShort(response.getMessage());
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
//                EventBus.getDefault().post(new EventBusEntity(5));
            }

            @Override
            public void onComplete() {
                super.onComplete();
            }
        });

    }

    /**
     * 年龄
     *
     * @param birth
     */
    public void onYearMonthDayPicker(TextView birth) {
        Calendar now = Calendar.getInstance();
        final DatePicker picker = new DatePicker(this);
        picker.setTopPadding(ConvertUtils.toPx(this, 10));
        picker.setRangeStart(1940, 1, 1);
        picker.setRangeEnd(now.get(Calendar.YEAR), (now.get(Calendar.MONTH) + 1), now.get(Calendar.DAY_OF_MONTH));
        picker.setTitleText("日期");
        picker.setTitleTextColor(CommonUtil.getColor(R.color.color_FFF8494A));
        picker.setSubmitText("确定");
        picker.setSubmitTextColor(CommonUtil.getColor(R.color.color_FFF8494A));
        picker.setCancelText("取消");
        picker.setTextColor(CommonUtil.getColor(R.color.color_FFF8494A));
        picker.setCancelTextColor(CommonUtil.getColor(R.color.color_FFF8494A));
        picker.setBackgroundResource(R.drawable.bg_white_6dp);
        WheelView.LineConfig lineConfig = new WheelView.LineConfig();
        lineConfig.setAlpha(255);//线透明度
        lineConfig.setColor(CommonUtil.getColor(R.color.color_FFF8494A));
        picker.setLineConfig(lineConfig);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                //保存出生日
                String ymd = year + "-" + month + "-" + day;
                birth.setText(ymd);
                birthday = ymd;
            }
        });
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });
        String str = "2000年01月01日";
        String s[] = str.split("(年|月|日)");
        picker.setSelectedItem(Integer.parseInt(s[0]), Integer.parseInt(s[1]), Integer.parseInt(s[2]));
        picker.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            if (data != null) {
                avatar = Matisse.obtainResult(data);
                if (avatar != null && avatar.size() > 0) {
                    Log.e("OnActivityResult ", String.valueOf(avatar.get(0)));
                    GlideUtils.loadImage(this, avatar.get(0).toString(), ivPersonHeader);
                    File file = null;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                        file = CommonUtil.uriToFileApiQ(this, avatar.get(0));
                    } else {
                        file = CommonUtil.uri2File(this, avatar.get(0));
                    }
                    updateByImgUrl(file);
                }
            }
        }
    }

    private void updateByImgUrl(File imaUrl) {
        Log.e("OnActivityResult2 ", imaUrl.toString());
        TreeMap<String, String> mapType = new TreeMap<>();
        mapType.put("type", "headImg");
//        File file = ScreenShotHelper.compressImage2(CommonUtil.getImage(imaUrl.getPath()), this);
        TreeMap<String, File> mapFile = new TreeMap<>();
        mapFile.put("file", imaUrl);
        showDialog("上传图片中...", false);
        new UserAPI().putFile(mapType, mapFile, new BaseResultCallback<PictrueEntity>() {
            @Override
            public void onResponse(PictrueEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    if (response.data != null) {
                        Message message = new Message();
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        bundle.putString("headImgUrl", response.data.url);
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                }
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Bundle bundle = msg.getData();
                    String headUrl = bundle.getString("headImgUrl");
                    headImgUrl = headUrl;
                    break;
            }
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusEntity event) {
        switch (event.getMsg()) {
            case 4:
                finish();
                break;
            default:
                break;
        }
    }
}